#include "webserver.h"

static volatile int serverOn = 1;


void servAdmin();
void webServ();
void admRead(SOCKET socket, char *line, int len);

void main(){

	WSADATA wsaData;
	WORD wVersionRequested = MAKEWORD( 2, 2 );
	int err = WSAStartup( wVersionRequested, &wsaData );

	initConf();

	_beginthread(webServ, 0, NULL);
	_beginthread(servAdmin, 0, NULL);
	while ( _getch() != 'q' );

	WSACleanup();

}

void webServ() {
	SOCKET clisocket;
	SOCKET mastersocket;
		
	mastersocket = initSocket(getHTTPPort());	
	listen(mastersocket, MAX_THREADS);
	
	while(1){
		if ( serverOn ) {
			clisocket = getClientSocket(mastersocket);					
			_beginthread(clientThread, 0, &clisocket);
		}
	}
}

void servAdmin() {
	SOCKET adminsocket, admin;
	int lineLen = 64, loggedIn = 0;
	char line[64], *wMsg = "Drone 1.23 serveradministrator.\n\rPlease enter command:", msg[128];
	
	adminsocket = initSocket(getAdminPort());	
	listen(adminsocket, 1);

	while(1) {
		admin = getClientSocket(adminsocket);
		
		while(1) {
			send(admin, wMsg, strlen(wMsg), 0);
			admRead(admin, line, lineLen);
			if ( loggedIn ) {
				if ( !strcmp(line, "START") ) {
					serverOn = 1;
					strcpy(msg, "server turned on");
					send(admin, msg, strlen(msg), 0);
				} else if ( !strcmp(line, "STOP") ) {
					serverOn = 0;
					strcpy(msg, "server turned off");
					send(admin, msg, strlen(msg), 0);
				} else if ( !strcmp(line, "LOGG") ) {
					sendLog(admin);
				} else if ( !strcmp(line, "QUIT") ) {					
					strcpy(msg, "Tank juice for using aur redonkulous server!");
					send(admin, msg, strlen(msg), 0);
					shutdown(admin, 2);
					loggedIn = 0;
					break;
				} else {
				}
			} else {
				if ( !strcmp(line, getAdminPassword()) ) {
					strcpy(msg, "Password ok\n\r");
					send(admin, msg, strlen(msg), 0);
					loggedIn = 1;					
				}
				else {
					strcpy(msg, "The password is incorrect!");
					send(admin, msg, strlen(msg), 0);
					shutdown(admin, 2);
					break;
				}
			}
		}
	}
}

void admRead(SOCKET socket, char *line, int len) {

	char buffer;
	char *p = line;
	int readOk;

	while ((readOk = recv(socket, &buffer, sizeof(buffer), 0)) > 0 && p < line + len){
		if ( buffer == '\n' ) {
			*(--p) = '\0';
				break;
		}
		*p = buffer;		
		p++;		
	}

}

//void admMenu(SOCKET socket) {
	